package org.hjl.commonutils.random;

import java.util.Random;

/**
 * @author hjl
 * @since 2024-08-05
 */
public class RandomUtil {

    private static final String ALL_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String DIGITS = "0123456789";
    private static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String generateRandomString(int count) {
        StringBuilder result = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < count; i++) {
            int randomIndex = random.nextInt(ALL_CHARACTERS.length());
            result.append(ALL_CHARACTERS.charAt(randomIndex));
        }
        return result.toString();
    }

    /**
     * 生成指定长度的数字
     *
     * @param count 长度
     * @return 数字
     */
    public static int generateRandomNumber(int count) {
        Random random = new Random();
        int max = (int) Math.pow(10, count);
        return random.nextInt(max);
    }

    /**
     * 生成指定长度的数字字符串
     *
     * @param count 长度
     * @return 数字字符串
     */
    public static String generateRandomNumberStr(int count) {
        return String.valueOf(generateRandomNumber(count));
    }

    /**
     * 生成混合字符串
     *
     * @param n 总长度
     * @param x 字符串长度
     * @param y 数字长度
     * @return 混合字符串
     */
    public static String generateMixedString(int n, int x, int y) {
        StringBuilder result = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < x; i++) {
            int randomIndex = random.nextInt(LETTERS.length());
            result.append(LETTERS.charAt(randomIndex));
        }

        for (int i = 0; i < y; i++) {
            int randomIndex = random.nextInt(DIGITS.length());
            result.append(DIGITS.charAt(randomIndex));
        }

        // 如果生成的字符总数不足 n，随机补充剩余字符
        while (result.length() < n) {
            int randomIndex = random.nextInt(ALL_CHARACTERS.length());
            result.append(ALL_CHARACTERS.charAt(randomIndex));
        }

        // 打乱字符串顺序
        char[] charArray = result.toString().toCharArray();
        for (int i = charArray.length - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            char temp = charArray[i];
            charArray[i] = charArray[j];
            charArray[j] = temp;
        }

        return new String(charArray);
    }

}